package com.jshoperxms.components.wechat.wxcode;

import com.jshoperxms.components.netease.nos.NosKeys;
import com.jshoperxms.components.upload.FileTools;
import com.jshoperxms.components.wechat.WxTokenUtils;
import com.jshoperxms.controller.mall.backstage.base.BaseTController;
import com.jshoperxms.controller.utils.DateTools;
import com.jshoperxms.controller.utils.statickey.StaticKey;
import com.netease.cloud.auth.BasicCredentials;
import com.netease.cloud.auth.Credentials;
import com.netease.cloud.services.nos.NosClient;
import com.netease.cloud.services.nos.model.ObjectMetadata;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * Created by sdywcd on 2019/1/30.
 * Des:
 */
@Component
public class WxacodeunlimitController extends BaseTController {

    @Autowired
    private WxTokenUtils wxTokenUtils;


    /**
     * 创建音频朗读二维码
     * @param sceneparams
     * @return
     */
    public Map<String,Object> createYdRecordWxCode(HttpServletRequest request, String sceneparams) {
        Map<String, Object> responsedata = new HashMap<>();
        String accessToken = wxTokenUtils.getToken();
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            JSONObject json=new JSONObject();
            json.put("scene",sceneparams);
            json.put("page","pages/share/viewrecord");
            json.put("width",430);
            json.put("auto_color", false);
            HttpClient client=new DefaultHttpClient();
            HttpPost post=new HttpPost(url);
            post.setHeader("Content-Type","application/json");
            String result="";
            StringEntity stringEntity=new StringEntity(json.toString(),"utf-8");
            stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
            post.setEntity(stringEntity);
            HttpResponse httpResponse=client.execute(post);
            inputStream=httpResponse.getEntity().getContent();



            String newFileFullname = StaticKey.EMPTY;// 包含后缀的文件名
            String nowTimeStr = StaticKey.EMPTY;
            String realpath = FileTools.isExistdir();
            SimpleDateFormat sDateFormat;
            Random r = new Random();
            String savePath = request.getSession().getServletContext().getRealPath(
                    File.separator);
            savePath = savePath + realpath;
            int rannum = (int) (r.nextDouble() * (99999 - 1000 + 1)) + 10000;
            sDateFormat = new SimpleDateFormat(DateTools.DF_YYYYMMDDHHMMSS);
            nowTimeStr = sDateFormat.format(new Date());
            newFileFullname = nowTimeStr + rannum;
            //文件的保存地址
            String filePath = savePath + newFileFullname + ".png";
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();

            String cloudFileKey = realpath + newFileFullname + ".png";// 云上的文件名称
            cloudFileKey = cloudFileKey.replace('\\', '/');
            Credentials credentials = new BasicCredentials(NosKeys.ACCESSKEY, NosKeys.ACCESSSECRET);
            NosClient nosClient = new NosClient(credentials);
            nosClient.setEndpoint(NosKeys.ENDPOINT);
            nosClient.putObject(NosKeys.BUCKET_LANGDUNENGSHOU_SHARECODE, cloudFileKey, new File(filePath));
            responsedata.put("wxcodeurl", NosKeys.LANGDUNENGSHOU_SHARECODE_PUBLICURL + cloudFileKey);
        } catch (IOException e) {

        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return responsedata;
    }



    /**
     * 创建音频图文朗读二维码
     * @param sceneparams
     * @return
     */
    public Map<String,Object> createYdTeamArtRecordWxCode(HttpServletRequest request, String sceneparams) {
        Map<String, Object> responsedata = new HashMap<>();
        String accessToken = wxTokenUtils.getToken();
        String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            JSONObject json=new JSONObject();
            json.put("scene",sceneparams);
            json.put("page","pages/share/viewtmemberartrecord");
            json.put("width",430);
            json.put("auto_color", false);
            HttpClient client=new DefaultHttpClient();
            HttpPost post=new HttpPost(url);
            post.setHeader("Content-Type","application/json");
            String result="";
            StringEntity stringEntity=new StringEntity(json.toString(),"utf-8");
            stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json"));
            post.setEntity(stringEntity);
            HttpResponse httpResponse=client.execute(post);
            inputStream=httpResponse.getEntity().getContent();



            String newFileFullname = StaticKey.EMPTY;// 包含后缀的文件名
            String nowTimeStr = StaticKey.EMPTY;
            String realpath = FileTools.isExistdir();
            SimpleDateFormat sDateFormat;
            Random r = new Random();
            String savePath = request.getSession().getServletContext().getRealPath(
                    File.separator);
            savePath = savePath + realpath;
            int rannum = (int) (r.nextDouble() * (99999 - 1000 + 1)) + 10000;
            sDateFormat = new SimpleDateFormat(DateTools.DF_YYYYMMDDHHMMSS);
            nowTimeStr = sDateFormat.format(new Date());
            newFileFullname = nowTimeStr + rannum;
            //文件的保存地址
            String filePath = savePath + newFileFullname + ".png";
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();

            String cloudFileKey = realpath + newFileFullname + ".png";// 云上的文件名称
            cloudFileKey = cloudFileKey.replace('\\', '/');
            Credentials credentials = new BasicCredentials(NosKeys.ACCESSKEY, NosKeys.ACCESSSECRET);
            NosClient nosClient = new NosClient(credentials);
            nosClient.setEndpoint(NosKeys.ENDPOINT);
            nosClient.putObject(NosKeys.BUCKET_LANGDUNENGSHOU_SHARECODE, cloudFileKey, new File(filePath));
            responsedata.put("wxcodeurl", NosKeys.LANGDUNENGSHOU_SHARECODE_PUBLICURL + cloudFileKey);
        } catch (IOException e) {

        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        return responsedata;
    }
}
